package com.it.ssh.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.it.ssh.dao.BookDao;
import com.it.ssh.entity.Book;
import com.it.ssh.tools.TimeTransform;


public class BookDaoImpl implements BookDao {
	private SessionFactory sessionFactory;
	

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	

	@Override
	public boolean add(Book book) {
		Session session = sessionFactory.openSession();
		Transaction tran=session.beginTransaction();
		session.save(book);
		tran.commit();
		return true;
	}

	@Override
	public boolean update(Book book) {
		Session session = sessionFactory.openSession();
		Transaction tran=session.beginTransaction();
		TimeTransform ts = new TimeTransform();
		session.update(book);
		tran.commit();
		return true;
	}

	@Override
	public boolean delete(int id) {
		Session session = sessionFactory.openSession();
		Transaction tran=session.beginTransaction();
		Book book = new Book();
		book.setId(id);
		session.delete(book);
		tran.commit();
		return true;
	}

	@Override
	public Book queryById(int id) {
		String hql = "from Book where id =?";
		Session session=sessionFactory.openSession();
		Query q=session.createQuery(hql);
		q.setInteger(0,id);
		Book book = new Book();
		if(q.uniqueResult()!=null){
			book=(Book) q.uniqueResult();
		}
		session.close();
		return book;
	}

	@Override
	public List<Book> queryAll() {
		String hql="from Book order by id asc";
		Session session=sessionFactory.openSession();
		Query q=session.createQuery(hql);
		List<Book> list=q.list();
		TimeTransform ts = new TimeTransform();
		for(Book b:list) {
		b.setPublishdate(ts.Stringtodate(ts.Datetostring(b.getPublishdate())));
		}
		session.close();
		return list;
	}

}
